"""
基础代理类
"""
import requests
import json
import logging
from typing import Dict, Any, Optional
from langchain.prompts import PromptTemplate
from .state import ReportState, AgentStatus
from .config import config
import time
import traceback
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

logger = logging.getLogger(__name__)

class BaseAgent:
    """基础代理类"""
    
    # 创建一个类级别的 session，所有实例共享
    _session = None
    
    @classmethod
    def get_session(cls):
        if cls._session is None:
            # 创建新的 session
            cls._session = requests.Session()
            
            # 配置重试策略
            retry_strategy = Retry(
                total=3,  # 最大重试次数
                backoff_factor=2,  # 重试间隔
                status_forcelist=[408, 429, 500, 502, 503, 504],
                allowed_methods=["POST"]
            )
            
            # 配置适配器
            adapter = HTTPAdapter(
                max_retries=retry_strategy,
                pool_connections=5,  # 连接池大小
                pool_maxsize=10,     # 最大连接数
                pool_block=True      # 连接池满时阻塞
            )
            
            # 挂载适配器
            cls._session.mount("https://", adapter)
            cls._session.mount("http://", adapter)
            
            logger.info("创建新的全局 session")
        return cls._session

    def __init__(self):
        logger.info(f"初始化 {self.__class__.__name__}...")
        self.name = None
        self.api_key = self._get_api_key()
        self.api_url = "https://api.siliconflow.cn/v1/chat/completions"
        self.model = "Pro/deepseek-ai/DeepSeek-V3"
        
        # 使用类级别的 session
        self.session = self.get_session()
        
        if not self.api_key:
            logger.warning(f"{self.__class__.__name__} API密钥未设置")
        
    def execute(self, state: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行代理任务
        
        Args:
            state: 当前状态
            
        Returns:
            Dict[str, Any]: 执行结果
        """
        raise NotImplementedError("子类必须实现execute方法")
    
    def _get_api_key(self) -> Optional[str]:
        """获取API密钥"""
        import os
        token = os.getenv('SILICONFLOW_API_KEY')
        if not token:
            logger.warning("未找到 SILICONFLOW_API_KEY 环境变量")
            token = os.getenv('OPENAI_API_KEY')
            if not token:
                logger.error("未找到任何可用的 API Token")
        return token
    
    def create_prompt(self, template: str, **kwargs) -> str:
        """
        创建提示词
        
        Args:
            template: 提示词模板
            **kwargs: 模板参数
            
        Returns:
            str: 格式化后的提示词
        """
        try:
            return template.format(**kwargs)
        except KeyError as e:
            logger.error(f"提示词模板参数缺失: {e}")
            return template
    
    def call_llm(self, messages: list, max_tokens: int = 2000, temperature: float = 0.7) -> Dict[str, Any]:
        """
        调用大语言模型
        
        Args:
            messages: 消息列表
            max_tokens: 最大token数
            temperature: 温度参数
            
        Returns:
            Dict[str, Any]: LLM响应结果
        """
        try:
            if not self.api_key:
                return {
                    "success": False,
                    "error": "API密钥未设置",
                    "content": ""
                }
            
            payload = {
                "model": self.model,
                "messages": messages,
                "stream": False,
                "max_tokens": max_tokens,
                "temperature": temperature,
                "top_p": 0.7,
                "top_k": 50,
                "frequency_penalty": 0.5,
                "n": 1,
                "response_format": {"type": "text"}
            }
            
            headers = {
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json",
                "Connection": "keep-alive"
            }
            
            logger.info(f"调用SiliconFlow API - {self.name}...")
            
            # 使用共享的 session 发送请求
            response = self.session.post(
                self.api_url,
                json=payload,
                headers=headers,
                timeout=(5, 60)  # (连接超时, 读取超时)
            )
            
            if response.status_code == 200:
                result = response.json()
                content = result.get('choices', [{}])[0].get('message', {}).get('content', '')
                return {
                    "success": True,
                    "content": content,
                    "usage": result.get('usage', {}),
                    "model": result.get('model', self.model)
                }
            else:
                error_msg = f"API调用失败: {response.status_code} - {response.text}"
                logger.error(error_msg)
                return {
                    "success": False,
                    "error": error_msg,
                    "content": ""
                }
                
        except requests.exceptions.Timeout as e:
            error_msg = f"API调用超时: {str(e)}"
            logger.error(error_msg)
            return {
                "success": False,
                "error": error_msg,
                "content": ""
            }
            
        except requests.exceptions.RequestException as e:
            error_msg = f"API请求异常: {str(e)}"
            logger.error(error_msg)
            return {
                "success": False,
                "error": error_msg,
                "content": ""
            }
            
        except Exception as e:
            error_msg = f"LLM调用异常: {str(e)}"
            logger.error(error_msg)
            logger.error(f"异常详情: {traceback.format_exc()}")
            return {
                "success": False,
                "error": error_msg,
                "content": ""
            } 